package com.sitecsys.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sitecsys.config.Result;
import com.sitecsys.mapper.FTLUserMapper;
import com.sitecsys.mapper.TbUserMapper;
import com.sitecsys.pojo.FTLUser;
import com.sitecsys.pojo.Face;
import com.sitecsys.pojo.TbUser;
import com.sitecsys.pojo.result.FaceResult;
import com.sitecsys.server.FaceContrastServer;
import com.sitecsys.service.FTLUserService;
import com.sitecsys.service.TbUserService;
import com.sitecsys.utils.DefaultAvatarUtil;
import com.sitecsys.utils.JwtUtils;
import com.sitecsys.utils.TimeUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

@Service
public class FTLUserServiceImpl  extends ServiceImpl<FTLUserMapper, FTLUser> implements FTLUserService {
    @Autowired
    private FTLUserMapper ftlUserMapper;

    @Autowired
    FaceContrastServer faceContrastServer;

    private static final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public Result vef(String imageBase) {
//        imageBase = JSONUtil.parseObj(imageBase).getStr("imageBase");
        List<FTLUser> faceList = lambdaQuery().orderByDesc(FTLUser::getVefNum).list();
        FaceResult faceState = null;
        // 如果人脸库为空,则第一次登录为录入人脸
        if (faceList.size() == 0){
            return initFace(imageBase);
        }else {
            int faceLength = faceList.size();
            for (FTLUser face : faceList) {
                FaceResult faceResult = faceContrastServer.faceContrast(face.getFaceBase(), imageBase);
                // 是否比对成功
                if (faceResult.getCode() == FaceResult.SUCCESS_CODE ){
                    // 相似度是否大于80
                    if (faceResult.getScore() > FaceResult.SATISFY_SCORE){
//                        face.setFaceStatus(0);
                        if (face.getStatus() == 1){
                            // 成功
                        FTLUser ftlUser = new FTLUser();
                        ftlUser.setUserid(face.getUserid());
                        if (ftlUserMapper.selectById(face.getUserid()).getVefNum() == null){
                            ftlUser.setVefNum(0);
                        }
                        ftlUser.setVefNum(ftlUserMapper.selectById(face.getUserid()).getVefNum() + 1); // 先查询当前vefNum值

                        UpdateWrapper<FTLUser> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("userid", face.getUserid());
                        updateWrapper.set("vef_num", ftlUser.getVefNum());



                        faceResult.setMsg(TimeUtils.timeQuantum()+"好,"+face.getUsername());
                            faceResult.setName(face.getUsername());
                            Map<String,String> map = new HashMap<>();
                            map.put("score",String.valueOf(faceResult.getScore()));
                            map.put("faceName",faceResult.getName());
                            map.put("phone", String.valueOf(face.getPhone()));
                            map.put("password", face.getPassword());

//                            faceResult.setToken(JwtUtils.genereteToken(map));
//                            return faceResult;

                        String usertoken = JwtUtils.genereteToken(map);
                        JSONObject data = new JSONObject();
                        data.put("token", usertoken);
                        return Result.success("登录成功," + face.getUsername() + "," + TimeUtils.timeQuantum()+"好！", data);
                        }else {
                            // 失败 人脸被禁用
                            lambdaUpdate().set(FTLUser::getVefNum,face.getVefNum()+1).eq(FTLUser::getUserid,face.getUserid()).update();
                            faceResult.setMsg(face.getFaceName()+",当前人脸被禁用");
                            faceResult.setName(face.getFaceName());
                            faceState = faceResult;
                            return Result.error( "当前账户 被禁用",500);
//                            // 就算上一张人脸被禁用还得往下执行
//                            // 可能当前用户存在多张人脸，
//                            if (faceLength == 1){
//                                return Result.error( "人脸库不存在该人脸",500);
//                            }
//                            faceLength --;
                        }
                    }else {
                        // 人脸库没有检测到人脸
                        if (faceLength == 1){
                            // 判断当前人脸是否被禁用，如被禁用，提示被禁用
                            // 禁用优先级大于 没有检测到人脸
                            return faceState != null? Result.success(faceState) :Result.error("人脸库不存在该人脸",faceResult.getScore());
                        }
                        faceLength --;
                    }
                }else {
                    // 接口返回异常
                    return Result.error("人脸信息与账户信息不匹配",faceResult.getScore());
                }
            }
        }
        // 空异常
        return Result.error(FaceResult.NULL_ERROR,"空指针异常");
    }

    public Result initFace(String imageBase){
        FaceResult faceResult = new FaceResult();
        FTLUser face = new FTLUser();
        face.setFaceBase(imageBase);
        face.setCreateTime(new Date());
        face.setVefNum(0);
        face.setFaceName("admin");
        face.setStatus(0);
        boolean save = save(face);
        faceResult.setCode(FaceResult.INIT_FACE);
        faceResult.setMsg("人脸初始化"+(save?"成功":"失败")+","+(save?"请验证登录":"请稍后再试"));
        faceResult.setName(face.getFaceName());
        return Result.success(faceResult);
    }


    @Override
    public Result login(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String password = jsonObj.getString("password");
        String imageBase = jsonObj.getString("imageBase");
       if (imageBase != null && imageBase != ""){
//           imageBase = JSONUtil.parseObj(imageBase).getStr("imageBase");

           Result faceResult = vef(imageBase);

           return faceResult;
       }else {
           Map<String, String> map = new HashMap<>();
           FTLUser user = ftlUserMapper.login(phone, password);
           if (user == null) {
               return Result.error(1011,"用户名或密码错误");
           }
           if (user.getStatus() == 0){
               return Result.error(1023,"该用户已被禁用");
           }
           map.put("phone", String.valueOf(user.getPhone()));
           map.put("password", user.getPassword());
           String usertoken = JwtUtils.genereteToken(map);
           JSONObject data = new JSONObject();
           data.put("token", usertoken);
           return Result.success("登录成功",data);
       }
    }




    @Override
    public Result register(JSONObject jsonObj) {
        // 验证必填字段不为空
        if (StringUtils.hasText(jsonObj.getString("phone")) && StringUtils.hasText(jsonObj.getString("password")) &&
                jsonObj.getJSONArray("security") != null && jsonObj.getJSONArray("security").size() == 3) {


            FTLUser user = new FTLUser();
            String username = jsonObj.getString("username");

            // 检查用户名是否已存在
            FTLUser existedUser = ftlUserMapper.selectByUsername(username);
            if (existedUser != null) {
                return Result.error("该用户名已被注册，请选择其他用户名");
            }

            user.setUsername(username);
            user.setPhone(jsonObj.getString("phone"));
            user.setPassword(jsonObj.getString("password"));
            user.setIsmanager(0);

            byte[] userAvatarBytes;
            // 检查avatar字段是否存在并转换为字节数组
            String avatarStr = jsonObj.getString("avatar");
            if (StringUtils.hasText(avatarStr)) {
                try {
                    user.setAvatar(avatarStr);
                } catch (Exception e) {
                    log.error("将avatar字符串转换为字节失败", e);
                    return Result.error("设置头像失败");
                }
            }else{
                //若无上传头像图片，则从本地上传一张图片作为默认头像
//            userAvatarBytes = DefaultAvatarUtil.getDefaultAvatarBytes();
//            user.setAvatar(userAvatarBytes);
                userAvatarBytes = DefaultAvatarUtil.getDefaultAvatarBytes();
                String avatarString = Base64.getEncoder().encodeToString(userAvatarBytes);
                user.setAvatar(avatarString);
            }

            String Facebase = jsonObj.getString("faceBase");
//        user.setFacebase(jsonObj.getString("facebase"));
            if (StringUtils.hasText(Facebase)) {
                try {
                    user.setFaceBase(Facebase);
                } catch (Exception e) {
                    log.error("将avatar字符串转换为字节失败", e);
                    return Result.error("设置人脸失败");
                }
            }
            JSONArray securityArray = jsonObj.getJSONArray("security");
            JSONObject o1 = securityArray.getJSONObject(0);
            JSONObject o2 = securityArray.getJSONObject(1);
            JSONObject o3 = securityArray.getJSONObject(2);
            ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
            Timestamp updateTime = Timestamp.from(zdt.toInstant());
            user.setSecurityQ1(o1.getString("question1"));
            user.setSecurityQ2(o2.getString("question2"));
            user.setSecurityQ3(o3.getString("question3"));
            user.setSecurityA1(o1.getString("answer1"));
            user.setSecurityA2(o2.getString("answer2"));
            user.setSecurityA3(o3.getString("answer3"));
            user.setStatus(1);
            user.setCreateTime(updateTime);
            user.setVefNum(0);

            // 执行插入操作
            try {
                if (ftlUserMapper.insert(user) > 0) {
                    return Result.success("注册成功");
                } else {
                    return Result.error("用户注册失败，请稍后重试");
                }
            } catch (Exception e) {
                log.error("用户注册时发生错误", e);
                return Result.error("服务器内部错误，请联系管理员");
            }
        }
        return Result.error("缺少必要的注册信息");
    }



    public Result getUserByPhone(HttpServletRequest request) {
        String token = request.getHeader("access-token");

        if (token == null) {
            return Result.error(1101,"Token not found");
        }

        try {

            DecodedJWT jwt = JwtUtils.getTokenInfo(token);
            String phone = jwt.getClaim("phone").asString();

            if (phone != null) {
                // 根据电话号码查询用户
                FTLUser user = ftlUserMapper.selectByPhone(phone);
                if (user != null) {
                    return Result.success("查询成功", user);
                } else {
                    return Result.error(1013,"User not found");
                }
            } else {
                return Result.error(1011,"Token payload doesn't contain phone information");
            }
        } catch (ExpiredJwtException e) {
            return Result.error(1012,"Token expired");
        } catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            return Result.error(1012,"Invalid token");
        }
        catch (Exception e) {
            return Result.error(1014,"token令牌已过期");
        }
    }

    @Override
    public Result getUserByPhoneAndName(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String username = jsonObj.getString("username");
        FTLUser user = ftlUserMapper.selectByPhoneAndName(phone, username);
        if (user!= null) {
            return Result.success("查询成功",user);
        }
        return Result.error(1015,"该用户不存在");
    }


    public Result updateUserById(JSONObject jsonObj) {

        Long id = jsonObj.getLong("userid");
        String phone = jsonObj.getString("phone");
        String username = jsonObj.getString("username");
        String avatar = jsonObj.getString("avatar");
        String ImageBase = jsonObj.getString("faceBase");
        String Q1 = jsonObj.getString("securityQ1");
        String Q2 = jsonObj.getString("securityQ2");
        String Q3 = jsonObj.getString("securityQ3");
        String A1 = jsonObj.getString("securityA1");
        String A2 = jsonObj.getString("securityA2");
        String A3 = jsonObj.getString("securityA3");
        Integer status = jsonObj.getInteger("status");
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Timestamp updateTime = Timestamp.from(zdt.toInstant());
        if(status != null){
            Boolean flag = ftlUserMapper.updateUserById(id, phone, username, status, avatar, ImageBase, Q1, Q2, Q3, A1, A2, A3, updateTime);
            if (flag){
                return Result.success("修改成功");
            }else {
                return Result.error(1017,"修改失败");
            }
        }
        if (ImageBase != null && ImageBase !=""){
            Boolean flag = ftlUserMapper.updateUserById(id, phone, username, null, null, ImageBase, Q1, Q2, Q3, A1, A2, A3, updateTime);
            if (flag){
                return Result.success("修改成功");
            }else {
                return Result.error(1017,"修改失败");
            }
        }
        Boolean flag = ftlUserMapper.updateUserById(id, phone, username, null, null, null, Q1, Q2, Q3, A1, A2, A3, updateTime);
        if (flag){
            return Result.success("修改成功");
        }else {
            return Result.error(1017,"修改失败");
        }
    }



    @Override
    public Result CheckUserByPhone(JSONObject jsonObj) {
        String username = jsonObj.getString("username");
        String A1 = jsonObj.getString("securityA1");
        String A2 = jsonObj.getString("securityA2");
        String A3 = jsonObj.getString("securityA3");
        FTLUser user = ftlUserMapper.selectByUsername(username);
        if ((A1.equals(user.getSecurityA1())) && (A2.equals(user.getSecurityA2())) && (A3.equals(user.getSecurityA3()))){
            return Result.success("密保问题通过！",200);
        }
        return Result.error(1016,"密保问题回答错误");
    }


    public Result updatePassword(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String newPwd = jsonObj.getString("newPwd");
        FTLUser user = ftlUserMapper.selectByPhone(phone);
        if (user.getPassword().equals(newPwd)) {
            return Result.error("新密码不能与原密码相同");

        } else {
            user.setPassword(newPwd);
            user.setUpdateTime(new Date());
            ftlUserMapper.updateById(user);
            return Result.success("修改成功");
        }

    }

    @Override
    public Result checkUserByFace(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String username = jsonObj.getString("username");
        String imageBase = jsonObj.getString("imageBase");

        if (ftlUserMapper.selectByPhoneAndName(phone, username) != null) {

            List<FTLUser> faceList = lambdaQuery().orderByDesc(FTLUser::getVefNum).list();
            FaceResult faceState = null;

            int faceLength = faceList.size();
//            FTLUser ftlUser = new FTLUser();
             FTLUser user = ftlUserMapper.selectByPhone(phone);
            FaceResult faceResult = faceContrastServer.faceContrast(user.getFaceBase(), imageBase);
                // 是否比对成功
                if (faceResult.getCode() == FaceResult.SUCCESS_CODE ){
                    // 相似度是否大于80
                    if (faceResult.getScore() > FaceResult.SATISFY_SCORE){
//                        face.setFaceStatus(0);
                        if (user.getStatus() == 1){
                            // 成功

                            user.setUserid(user.getUserid());
                            if (ftlUserMapper.selectById(user.getUserid()).getVefNum() == null){
                                user.setVefNum(0);
                            }
                            user.setVefNum(ftlUserMapper.selectById(user.getUserid()).getVefNum() + 1); // 先查询当前vefNum值

                            UpdateWrapper<FTLUser> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("userid", user.getUserid());
                            updateWrapper.set("vef_num", user.getVefNum());
                            return Result.success("人脸对比成功");
                        }else {
                            // 失败 人脸被禁用
                            lambdaUpdate().set(FTLUser::getVefNum,user.getVefNum()+1).eq(FTLUser::getUserid,user.getUserid()).update();
                            faceResult.setMsg(user.getFaceName()+",当前人脸被禁用");
                            faceResult.setName(user.getFaceName());
                            faceResult.setCode(FaceResult.FORBIDDEN_FACE);
                            faceState = faceResult;
                            // 就算上一张人脸被禁用还得往下执行
                            // 可能当前用户存在多张人脸，
                            if (faceLength == 1){
                                return Result.success(faceResult);
                            }
                            faceLength --;
                        }
                    }else {
                        // 人脸库没有检测到人脸
                        if (faceLength == 1){
                            // 判断当前人脸是否被禁用，如被禁用，提示被禁用
                            // 禁用优先级大于 没有检测到人脸
                            return faceState != null? Result.success(faceState) :Result.error("人脸库不存在该人脸",faceResult.getScore());
                        }
                        faceLength --;
                    }
                }else {
                    // 接口返回异常
                    return Result.error("人脸信息与账户信息不匹配");
                }
            }

            // 空异常
            return Result.error(FaceResult.NULL_ERROR,"人脸信息与账户信息不匹配");
        }

    @Override
    public Result newPwdUpdate(JSONObject jsonObj, HttpServletRequest request) throws Exception {
        String token = request.getHeader("access-token");
        DecodedJWT jwt = JwtUtils.getTokenInfo(token);
        String phone = jwt.getClaim("phone").asString();
        String orgPwd = jwt.getClaim("password").asString();
        String OldPwd = jsonObj.getString("oldPwd");
        String newPwd = jsonObj.getString("newPwd");
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Timestamp updateTime = Timestamp.from(zdt.toInstant());
        System.out.println("orgPwd:"+orgPwd+"OldPwd:"+OldPwd+"newPwd:"+newPwd);
        if (orgPwd.equals(OldPwd)){
            FTLUser user = ftlUserMapper.selectByPhone(phone);
            user.setPassword(newPwd);
            user.setUpdateTime(updateTime);
            ftlUserMapper.updateById(user);
            return Result.success("修改成功",200);
        }else {
            return Result.error("原密码错误",1019);
        }

    }

    @Override
    public Result uploadImage(JSONObject jsonObj, HttpServletRequest request) throws Exception {

        String token = request.getHeader("access-token");
        DecodedJWT jwt = JwtUtils.getTokenInfo(token);
        String phone = jwt.getClaim("phone").asString();
        String imageBase = jsonObj.getString("newFacebase");
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Timestamp updateTime = Timestamp.from(zdt.toInstant());
        Boolean flag = ftlUserMapper.updateImageByPhone(phone, imageBase, updateTime);
        if (flag){
            return Result.success("人像更新成功!",200);
        }else {
            return Result.error("人像更新失败!",1020);
        }
    }

    @Override
    public Result updateAvatar(JSONObject jsonObj, HttpServletRequest request) throws Exception {
        String token = request.getHeader("access-token");
        DecodedJWT jwt = JwtUtils.getTokenInfo(token);
        String phone = jwt.getClaim("phone").asString();
        String avatar = jsonObj.getString("avatar");

        Boolean flag = ftlUserMapper.updateAvatarByPhone(phone, avatar);
        if (flag){
            return Result.success("头像更新成功!",200);
        }
        return Result.error("头像更新失败!",1021);

    }

    @Override
    public Result getUsers(JSONObject jsonObj, HttpServletRequest request) throws Exception {
        String token = request.getHeader("access-token");
        DecodedJWT jwt = JwtUtils.getTokenInfo(token);
        String phone = jwt.getClaim("phone").asString();
        Integer tpye = jsonObj.getInteger("type");
        Integer page = jsonObj.getInteger("page");
        Integer size = jsonObj.getInteger("pageSize");
        HashMap<String, Object> map = new HashMap<>();
        Integer flag = ftlUserMapper.CheckIsManager(phone);
        if (flag == 1 || flag == 2){
            if (tpye == 0){
                List<FTLUser> list = ftlUserMapper.getUsersByIsManagerN((page - 1) * size, size);
                map.put("total", ftlUserMapper.getUsersCount(flag));
                map.put("userList", list);
                return Result.success(map);
            }else if (tpye == 1){
                List<FTLUser> list = ftlUserMapper.getUsersByIsManagerY((page - 1) * size, size);
                for (FTLUser usr: ftlUserMapper.getSuper()) {
                    list.add(usr);
                }
                map.put("total", ftlUserMapper.getUsersCount(flag) + 1);
                map.put("userList", list);
                return Result.success(map);
            } else if(tpye == 2) {
                List<FTLUser> list = ftlUserMapper.getUsers((page - 1) * size, size);
                map.put("total", ftlUserMapper.getUsersCounts());
                map.put("userList", list);
                return Result.success(map);
            }
        }else {
            return Result.error("无权限",1022);
        }
        return Result.error("参数错误",1023);
    }

    @Override
    public Result getUsersByAdvSearch(JSONObject jsonObj, HttpServletRequest request) throws ParseException {
        String username = jsonObj.getString("username");
        Integer auth = jsonObj.getInteger("auth");
        Integer status = jsonObj.getInteger("status");
        Integer page = jsonObj.getInteger("page");
        Integer size = jsonObj.getInteger("pageSize");
        HashMap<String, Object> map = new HashMap<>();
        String startTime = jsonObj.getString("startTime");
        String endTime = jsonObj.getString("endTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!"".equals(startTime) && !"".equals(endTime)){
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
            Timestamp startTimestamp = new Timestamp(startDate.getTime());
            Timestamp endTimestamp = new Timestamp(endDate.getTime());
            List<FTLUser> usersSize = ftlUserMapper.getUsersByAdvSearch(username, auth, status,startTimestamp, endTimestamp,  null, null);
            List<FTLUser> usersByAdvSearch = ftlUserMapper.getUsersByAdvSearch(username, auth, status,startTimestamp, endTimestamp,(page - 1) * size, size);
            if(auth != null){
                if (auth==1){
                    List<FTLUser> superUser = ftlUserMapper.getSuper();
                    for (FTLUser usr : superUser){
                        usersByAdvSearch.add(usr);
                    }
                }
            }
            map.put("total", usersSize.size());
            map.put("userList", usersByAdvSearch);
            return Result.success("查询成功",map);
        }else {
        List<FTLUser> usersSize = ftlUserMapper.getUsersByAdvSearch(username, auth, status,null, null,  null, null);
        List<FTLUser> usersByAdvSearch = ftlUserMapper.getUsersByAdvSearch(username, auth,status, null, null,  (page - 1) * size, size);
            if(auth != null){
                if (auth==1){
                    List<FTLUser> superUser = ftlUserMapper.getSuper();
                    for (FTLUser usr : superUser){
                        usersByAdvSearch.add(usr);
                    }
                }
            }
        map.put("total", usersSize.size());
        map.put("userList", usersByAdvSearch);
        return Result.success("查询成功",map);
        }
    }

    @Override
    public Result getUserById(JSONObject jsonObj) {
        FTLUser user = ftlUserMapper.selectById(jsonObj.getInteger("userid"));
        if (user != null){
            return Result.success("查询成功",user);
        }
        return Result.error("用户不存在");
    }

    @Override
    public Result delById(JSONObject jsonObj) {
        Boolean flag = ftlUserMapper.deleteByUserId(jsonObj.getInteger("userid"));
        if (flag){
            return Result.success("删除成功",200);
        }
        return Result.error("删除失败",1028);
    }

    @Override
    public Result reSetPwd(JSONObject jsonObj) {
        JSONArray jsonArray = jsonObj.getJSONArray("userIdArray");
        List<Long> userIdArray = jsonArray.toJavaList(Long.class);
        String RePwd = "123456@abc";
        Boolean flag = ftlUserMapper.reSetPwdById(userIdArray, RePwd);
        if (flag){
            return Result.success("重置成功",200);
        }
        return Result.error("重置失败",1029);
    }

    @Override
    public Result batchDel(JSONObject jsonObj) {
        JSONArray jsonArray = jsonObj.getJSONArray("userIdArray");
        List<Long> userIdArray = jsonArray.toJavaList(Long.class);
         Boolean flag = ftlUserMapper.batchDelById(userIdArray);
         if (flag){
            return Result.success("批量删除成功",200);
        }
        return Result.error( "批量删除失败",1030);
    }

    @Override
    public Result batchResetStatus(JSONObject jsonObj) {

        JSONArray jsonArray = jsonObj.getJSONArray("userIdArray");
        Integer type = jsonObj.getInteger("type");
        List<Integer> userIdArray = jsonArray.toJavaList(Integer.class);
        Boolean flag = ftlUserMapper.batchResetStatus(type,userIdArray);
        if (flag){
            return Result.success("批量重置成功",200);
        }
        return Result.error("批量重置失败",1031);
    }

    @Override
    public Result getAuth(JSONObject jsonObj) {

        FTLUser user = ftlUserMapper.selectById(jsonObj.getInteger("userid"));
        Integer auth = user.getIsmanager();
        Map<Object, Object> map = new HashMap<>();

        if (auth == 1){
            map.put("userid", user.getUserid());
            map.put("auth", auth);
            map.put(""+user.getUserid()+user.getUsername(),user.getIsmanager());
            map.put("description", "管理员");
            return Result.success("获取成功",map);
        }else if (auth == 2){
            map.put("userid", user.getUserid());
            map.put("auth", auth);
            map.put(""+user.getUserid()+user.getUsername(),user.getIsmanager());
            map.put("description", "超级管理员");
            return Result.success("获取成功",map);
        }else if (auth == 0){
            map.put("userid", user.getUserid());
            map.put("auth", auth);
            map.put(""+user.getUserid()+user.getUsername(),user.getIsmanager());
            map.put("description", "用户");
            return Result.success("获取成功",map);
        }
        return Result.success("参数错误",1032);
    }

    @Override
    public Result updateAuth(JSONObject jsonObj) throws JsonProcessingException {
        JsonNode rootNode = objectMapper.readTree(String.valueOf(jsonObj));
        List<FTLUser> users = ftlUserMapper.getAllUser();
        rootNode.fields().forEachRemaining(entry -> {
            String key = entry.getKey();
            JsonNode value = entry.getValue();
            Optional<FTLUser> updatedUser = users.stream()
                    .filter(user -> key.equals("" + user.getUserid() + user.getUsername()))
                    .findFirst();
            updatedUser.ifPresent(user -> ftlUserMapper.updateAuth(user.getUserid(), value.asInt()));
        });

        return Result.Success("更新成功");
    }

    @Override
    public Result getAuths() {
        Map<String, Object> map = new HashMap<>();
        List<FTLUser> users = ftlUserMapper.getAllUser();
        for (FTLUser user : users) {
            map.put(""+user.getUserid()+user.getUsername(),user.getIsmanager());
        }
        return Result.success("获取成功",map);
    }

}
